package com.semeureka.fault.mina;

import java.net.Inet4Address;
import java.net.UnknownHostException;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.semeureka.fault.util.Message;
import com.semeureka.fault.util.MessageObserver;
import com.semeureka.frame.util.HexUtils;

public class MessageHandler extends IoHandlerAdapter {
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageHandler.class);
	private MessageObserver[] messageObservers;
	private Integer projectId;

	public void setMessageObservers(MessageObserver[] messageObservers) {
		this.messageObservers = messageObservers;
	}

	public void setProjectId(Integer projectId) {
		this.projectId = projectId;
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		if (projectId != null) {
			session.write(createProjectIdentity(projectId.toString()));
		}
	}

	private IoBuffer createProjectIdentity(String projectName) {
		IoBuffer buffer = IoBuffer.allocate(255);
		buffer.putUnsignedShort(0x0C1C); // 标记
		String ip = "127.0.0.1";
		try {
			ip = Inet4Address.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
		}
		buffer.putUnsignedShort(ip.length()); // 本机地址长度
		buffer.put(ip.getBytes()); // 本机地址
		buffer.putInt(0x0C1C0001); // 标记
		buffer.putUnsignedShort(projectName.length()); // 项目编号长度
		buffer.put(projectName.getBytes()); // 项目编号
		buffer.putUnsignedShort(HexUtils.modbusCrc(buffer, 0, buffer.position()));
		return buffer.flip();
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		LOGGER.error("处理 {} 的数据时发生异常：{}", session, cause);
		LOGGER.debug("详细异常信息：", cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		LOGGER.debug("已接收到来自 {} 的内容：{}", session, message);
		if (message instanceof Message) {
			for (MessageObserver messageObserver : messageObservers) {
				messageObserver.update((Message) message);
			}
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		LOGGER.debug("已发送到目标 {} 的内容：{}", session, message);
		if (message instanceof Message) {
			for (MessageObserver messageObserver : messageObservers) {
				messageObserver.update((Message) message);
			}
		}
	}
}
